package fr.ece.ing4.si.prof.stopwatch;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class StopWatch extends JFrame implements ActionListener {

	private static final long serialVersionUID = -8703843689450789725L;
	private boolean running;
	JButton startStopButton;
	JLabel timeLabel;

	@Override
	protected void frameInit() {
		super.frameInit();
		getContentPane().setLayout(new FlowLayout());
		startStopButton = new JButton();
		timeLabel = new JLabel();
		startStopButton.setText("Start");
		timeLabel.setText("0");
		getContentPane().add(startStopButton);
		getContentPane().add(timeLabel);

		startStopButton.addActionListener(this);
		this.setSize(200, 100);
		Thread c = new Thread(new Counter());
		this.setVisible(true);
		c.start();
	}

	public void actionPerformed(final ActionEvent event) {
		if (running)
			running = false;
		else
			running = true;
	}

	private class Counter implements Runnable {
		private void startCounting() {
			startStopButton.setText("Stop");
			for (int count = 0; running; count++) {
				timeLabel.setText(String.format("%d", count));
				try {
					Thread.sleep(1000);
				} catch (InterruptedException ex) {
					throw new RuntimeException(ex);
				}
			}
		}

		private void stopCounting() {
			startStopButton.setText("Start");
		}

		@Override
		public void run() {
			while (true) {
				if (running)
					startCounting();
				stopCounting();
			}
		}
	}
}
